package com.ruoyi.web.controller.sso;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.TypeReference;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.ExceptionUtil;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.UserDetailsServiceImpl;
import com.ruoyi.system.mapper.H5RegisterMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.web.controller.sso.domain.*;
import com.ruoyi.web.domain.WorkEnterpriseUser;
import com.ruoyi.web.service.NatureUserInfoService;
import com.ruoyi.web.service.WorkEnterpriseUserService;
import com.ruoyi.web.util.CreateSignUtil;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringEscapeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;
import sviolet.smcrypto.SmCryptoUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * description: 统一认证中心回调处理
 * auth fcb
 * date 2025-04-10 14:04
 **/
@Controller
@Api(tags = "统一认证中心")
@Slf4j
public class SSOController {

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysLoginService sysLoginService;
    @Autowired
    private H5RegisterMapper h5RegisterMapper;
    @Autowired
    private WorkEnterpriseUserService workEnterpriseUserService;
    @Autowired
    private NatureUserInfoService natureUserInfoService;

    /**
     * 这个接口应该是前端进行回调
     * @param request
     * @param response
     */
    @GetMapping("/callback")
    public void callback(HttpServletRequest request, HttpServletResponse response) {
        // 这个接口如果是我们前端请求的则携带该参数，否则则为空
        String status = request.getParameter("status");
        if(StringUtils.isEmpty(status)) {
            // 如果不是我们自己前端的回调，则记录下日志，不做其他处理
            log.info("【统一认证中心回调】status为空");
            this.logRequestHeader(request);
            this.logRequestParameter(request);
            return;
        }

        log.info("【统一认证中心回调】...");
        // 1. 假设统一认证中心，回调票据的参数叫 ticket
        String ticket = request.getParameter("ticket");
        if(StringUtils.isEmpty(ticket)) {
            log.error("【统一认证中心回调】ticket为空");
            this.sendError(response, "票据为空");
        }
        // 2. 请求签名。这里他们给了两种获取签名的方式，两种方式都可以，这里先使用接口的方式
        String timestamp_1 = System.currentTimeMillis() + "";
        String sign = this.requestAuthCenterSign("ticketValidate", timestamp_1, ticket, "ticket");
        //String sign = this.createSign();
        if(StringUtils.isEmpty(sign)) {
            log.error("【统一认证中心回调】请求签名失败");
            this.sendError(response,  "请求签名失败");
            return;
        }
        // 3. 使用票据请求token, sign是上面请求得到的
        String encryptedData= this.requestAuthCenterToken(sign, ticket, timestamp_1);
        if(StringUtils.isEmpty(encryptedData)) {
            log.error("【统一认证中心回调】请求token失败");
            this.sendError(response, "请求token失败");
            return;
        }
        // 4. 解密数据得到明文token。人家说token的过期时间是三天，不用考虑token过期的问题
        AuthCenterTokenData tokenData = this.decryptDataAndGetToken(encryptedData);
        if(tokenData == null) {
            log.error("【统一认证中心回调】解密并获取token失败");
            this.sendError(response, "解密token失败");
            return;
        }
        // 5.使用token获取用户信息。用户分为个人和法人，
        if(AuthCenterConst.USER_TYPE_NATURE.equals(tokenData.getUsertype())) {
//            log.info("【统一认证中心回调】用户类型为个人，返回跳转到注册页面的标识");
//            AjaxResult result = new AjaxResult(401, "跳转到注册页面");
//            this.sendSuccess(response, result);
            // 请求一个获取用户信息的签名
            String timestamp_user = System.currentTimeMillis() + "";
            String sign_user = this.requestAuthCenterSign("findPerUserByToken", timestamp_user, tokenData.getToken(), "token");
            if(StringUtils.isEmpty(sign_user)) {
                log.error("【统一认证中心回调】获取自然用户信息，请求签名失败");
                this.sendError(response,  "获取自然用户信息，请求签名失败");
                return;
            }
            String encodeNatureUserInfo = this.requestEncodeEnterpriseNatureUserInfo(tokenData.getToken(), sign_user, timestamp_user);
            if(StringUtils.isEmpty(encodeNatureUserInfo)) {
                log.error("【统一认证中心回调】请求自然人用户信息失败");
                this.sendError(response,  "请求自然人用户信息失败");
                return;
            }
            AuthNatureUserInfo natureUserInfo = this.decodeNatureUserInfo(encodeNatureUserInfo);
            if(natureUserInfo == null) {
                log.error("【统一认证中心回调】解密自然人用户信息失败");
                this.sendError(response,  "提取自然人用户信息失败");
                return;
            }
            try{
                natureUserInfoService.saveOrUpdateCenterUserInfo(natureUserInfo);
            }catch (Exception e) {
                log.error("【统一认证中心回调】保存自然人用户信息失败：{}", e.getMessage());
            }
            log.info("【统一认证中心回调】自然人用户信息：{}", JSON.toJSONString(natureUserInfo));
            // 判断该自然人是否绑定了企业，如果绑定了企业直接以企业身份登录，没有绑定企业，则直接跳转到绑定页面
            Integer enterpriseUserCount = workEnterpriseUserService.getEnterpriseUserCount(natureUserInfo.getUuid());
            if(enterpriseUserCount == 0) {
                AjaxResult result = new AjaxResult(401, "跳转到绑定企业页面",  natureUserInfo.getUuid());
                this.sendSuccess(response, result);
            }else if(enterpriseUserCount == 1) {
                // 查询绑定的企业信息，以企业身份登录
                WorkEnterpriseUser workEnterpriseUser = workEnterpriseUserService.getWorkEnterpriseUser(natureUserInfo.getUuid());
                String token = sysLoginService.login(workEnterpriseUser.getUnicode(), "", "", "", UserDetailsServiceImpl.AI_SHAN_DONG_SSO_FLAG);
                AjaxResult ajax = AjaxResult.success();
                ajax.put(Constants.TOKEN, token);
                this.sendSuccess(response, ajax);
            } else {
                log.error("【统一认证中心回调】自然人用户绑定了多个企业");
                this.sendError(response,  "用户企业关系异常");
            }
            return;
        }
        // 再次请求一个签名，用于请求法人用户信息
        String timestamp_2 = System.currentTimeMillis() + "";
        String sign2 = this.requestAuthCenterSign("findCorUserByToken", timestamp_2, tokenData.getToken(), "token");
        if(StringUtils.isEmpty(sign2)) {
            log.error("【统一认证中心回调】第二次请求签名失败");
            this.sendError(response,  "第二次请求签名失败");
            return;
        }
        String encodeUserInfo = this.requestEncodeEnterpriseUserInfo(tokenData.getToken(), sign2, timestamp_2);
        if(StringUtils.isEmpty(encodeUserInfo)) {
            log.error("【统一认证中心回调】请求企业用户信息失败");
            this.sendError(response,  "请求用户信息失败");
            return;
        }
        AuthEnterpriseUserInfo enterpriseUserInfo = this.decodeEnterpriseUserInfo(encodeUserInfo);
        if(enterpriseUserInfo == null) {
            log.error("【统一认证中心回调】解密企业用户信息失败");
            this.sendError(response,  "提取用户信息失败");
            return;
        }
        log.info("【统一认证中心回调】企业用户信息：{}", JSON.toJSONString(enterpriseUserInfo));
        // 在系统中的用户默认登录并返回登录后的token，不在系统中的用户，则创建用户，并登录后返回token
        String creditCode = enterpriseUserInfo.getCreditCode();// 统一社会信用代码
        AjaxResult ajaxResult = this.doLogin(creditCode);
        this.sendSuccess(response, ajaxResult);
    }

    /**
     * 登录系统，返回token
     * @param creditCode 统一社会信用代码
     * @return
     */
    private AjaxResult doLogin(String creditCode) {
        SysUser sysUser = sysUserMapper.checkUserNameUnique(creditCode);
        if(sysUser != null) {
            log.info("【统一认证中心回调】用户已存在，直接登录");
            String token = sysLoginService.login(sysUser.getUserName(), "", "", "", UserDetailsServiceImpl.AI_SHAN_DONG_SSO_FLAG);
            AjaxResult ajax = AjaxResult.success();
            ajax.put(Constants.TOKEN, token);
            return ajax;
        }else {
            log.info("【统一认证中心回调】用户不存在，创建用户");
            // 创建用户.
            // 在企业库中查询企业名称
            String companyName = sysUserMapper.queryCompanyNameByCode(creditCode);
            SysUser user = new SysUser();
            user.setUserName(creditCode);
            if(StringUtils.isEmpty(companyName)) {
                user.setNickName("");
            }else {
                user.setNickName(companyName);
            }
            String password = creditCode;
            if (creditCode.length() >= 6) {
                password = creditCode.substring(creditCode.length() - 6);
            }
            user.setPassword(SecurityUtils.encryptPassword(password));
            user.setRemark("企业人员");
            boolean regFlag = sysUserMapper.insertUser(user) > 0;
            if(!regFlag) {
                log.error("【统一认证中心回调】创建用户失败");
                return AjaxResult.error("创建用户失败");
            }
            Long userId = h5RegisterMapper.queryRegisterUserId(user.getUserName());
            if(userId == null) {
                log.error("【统一认证中心回调】创建用户失败");
                return AjaxResult.error("创建用户失败");
            }
            else {
                // 给用户添加普通角色，并登录
                h5RegisterMapper.insertRegisterUserRole(userId, 2L);
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(creditCode, Constants.REGISTER, MessageUtils.message("user.register.success")));
                String token = sysLoginService.login(creditCode, "", "", "", UserDetailsServiceImpl.AI_SHAN_DONG_SSO_FLAG);
                AjaxResult ajax = AjaxResult.success();
                ajax.put(Constants.TOKEN, token);
                return ajax;
            }
        }
    }

    private void logRequestHeader(HttpServletRequest request) {
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            String headerValue = request.getHeader(headerName);
            log.info("【统一认证中心回调】headerName={}, headerValue={}", headerName,headerValue);
        }
    }

    private void logRequestParameter(HttpServletRequest request) {
        Enumeration<String> parameterNames = request.getParameterNames();
        while (parameterNames.hasMoreElements()) {
            String parameterName = parameterNames.nextElement();
            String parameterValue = request.getParameter(parameterName);
            log.info("【统一认证中心回调】parameterName={}, parameterValue={}", parameterName,parameterValue);
        }
    }

    private void sendError(HttpServletResponse response, String message) {
        try {
            response.setStatus(200);
            response.setContentType("application/json;charset=utf-8");
            AjaxResult error = AjaxResult.error(message);
            response.getWriter().write(JSON.toJSONString(error));
        } catch (Exception e) {
            log.error("【统一认证中心回调】sendError error : {}", ExceptionUtil.getExceptionMessage(e));
        }
    }

    private void sendSuccess(HttpServletResponse response, AjaxResult success) {
        try {
            response.setStatus(200);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(JSON.toJSONString(success));
        } catch (Exception e) {
            log.error("【统一认证中心回调】sendSuccess error : {}", ExceptionUtil.getExceptionMessage(e));
        }
    }

    // 请求签名
    private String requestAuthCenterSign(String interfaceId, String timestamp, String ticketOrToken, String type) {
        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        params.add("app_id", AuthCenterConst.APP_ID);
        params.add("interface_id", interfaceId);
        params.add("version", "1.0");
        params.add("charset", "UTF-8");
        params.add("timestamp", timestamp);
        params.add("origin", "0");
        String bizContent = this.getBizContent(type, ticketOrToken);
        params.add("biz_content", bizContent);

        try {
            log.info("【请求统一认证签名】参数： {}", JSON.toJSONString(params));
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(params, headers);
            ResponseEntity<String> exchange = restTemplate.exchange(AuthCenterConst.AUTH_CENTER_SIGN_URL, HttpMethod.POST, requestEntity, String.class);
            if(!exchange.getStatusCode().is2xxSuccessful()) {
                log.error("【请求统一认证签名】请求失败 http status :{}", exchange.getStatusCode());
                return null;
            }
            String body = exchange.getBody();
            log.info("【请求统一认证签名】返回： {}", body);
            JSONObject jsonObject = JSON.parseObject(body);
            if(jsonObject != null && !jsonObject.getBooleanValue("success")) {
                log.error("【请求统一认证签名】接口返回success != true");
                return null;
            }
            JSONObject signObj = (JSONObject)jsonObject.get("data");
            return signObj.getString("sign");
        }catch (Exception e) {
            log.error("【请求统一认证签名】异常: {}", ExceptionUtil.getExceptionMessage(e));
            return null;
        }
    }

    // 当type=ticket时，参数为ticket，type=token时，参数为token
    private String getBizContent(String type, String ticketOrToken) {
        Map<String, String> bizContent = new HashMap<>();
        bizContent.put("appMark", AuthCenterConst.APP_ID);
        Map<String, String> bizContentParam = new HashMap<>();
        bizContentParam.put(type, ticketOrToken);
        bizContent.put("params", JSON.toJSONString(bizContentParam));
        return JSON.toJSONString(bizContent);
    }

    // 所给资料示例里面的参数
    private String createSign() {
        GatewayBean gatewayBean = new GatewayBean();
        gatewayBean.setAppUniqueId(AuthCenterConst.APP_ID);
        gatewayBean.setInterfaceUniqueId("");
        gatewayBean.setHeader("{}");

        Map<String, String> bizContent = new HashMap<>();
        bizContent.put("appMark", AuthCenterConst.APP_ID);
        // bizContent.put("params", "");

        gatewayBean.setBizContent(JSON.toJSONString(bizContent));
        gatewayBean.setCharset("UTF-8");
        gatewayBean.setTimestamp(String.valueOf(System.currentTimeMillis()));
        gatewayBean.setVersion("1");

        return CreateSignUtil.createSign(gatewayBean);
    }

    // 获取token，返回数据是加密的
    private String requestAuthCenterToken(String sign, String ticket, String timestamp) {

        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        params.add("app_id", AuthCenterConst.APP_ID);
        params.add("interface_id", "ticketValidate");
        params.add("version", "1.0");
        params.add("charset", "UTF-8");
        params.add("timestamp", timestamp);
        params.add("origin", "0");
        params.add("sign", sign);
        String bizContent = this.getBizContent("ticket", ticket);
        params.add("biz_content", bizContent);

        try {
            log.info("【请求统一认证签名】参数： {}", JSON.toJSONString(params));
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(params, headers);
            ResponseEntity<String> exchange = restTemplate.exchange(AuthCenterConst.AUTH_CENTER_TOKEN_URL, HttpMethod.POST, requestEntity, String.class);
            if(!exchange.getStatusCode().is2xxSuccessful()) {
                log.error("【请求统一认证token】请求失败, http status :{}", exchange.getStatusCode());
                return null;
            }
            String body = exchange.getBody();
            log.info("【请求统一认证token】返回： {}", body);
            JSONObject jsonObject = JSON.parseObject(body);
            if(jsonObject != null && !AuthCenterConst.AUTH_CENTER_SUCCESS_CODE.equals(jsonObject.getString("code"))) {
                log.error("【请求统一认证签名】接口返回code != 200");
                return null;
            }
            return jsonObject.getString("data");
        }catch (Exception e) {
            log.error("【请求统一认证token】异常: {}", ExceptionUtil.getExceptionMessage(e));
            return null;
        }
    }

    // 解密token数据并返回token
    private AuthCenterTokenData decryptDataAndGetToken(String data) {
        try {
            String content = SmCryptoUtil.sm2Decode(data, AuthCenterConst.sm2PrivateKey);
            log.info("【解密数据】解密数据： {}", content);
            if(StringUtils.isEmpty(content)) {
                log.error("【解密数据】解密数据为空");
                return null;
            }
            //content = StringEscapeUtils.unescapeJson(content);
            AuthCenterDecodeDataWrapper<String> dataWrapper = JSON.parseObject(content, new TypeReference<AuthCenterDecodeDataWrapper<String>>() {});
            if(!AuthCenterConst.DATA_SUCCESS_CODE.equals(dataWrapper.getRetcode())) {
                log.error("【解密数据获取】接口返回code != 000000, retcode:{}, msg:{}", dataWrapper.getRetcode(), dataWrapper.getMsg());
                return null;
            }

            return JSON.parseObject(dataWrapper.getData(), AuthCenterTokenData.class);
        }catch (Exception e) {
            log.error("【解密数据获取token】解密异常: {}", ExceptionUtil.getExceptionMessage(e));
            return null;
        }
    }

    // 获取企业用户信息，返回加密的数据
    private String requestEncodeEnterpriseUserInfo(String token, String sign, String timestamp) {

        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        params.add("app_id", AuthCenterConst.APP_ID);
        params.add("interface_id", "findCorUserByToken");
        params.add("version", "1.0");
        params.add("charset", "UTF-8");
        params.add("timestamp", timestamp);
        params.add("origin", "0");
        params.add("sign", sign);
        String bizContent = this.getBizContent("token", token);
        params.add("biz_content", bizContent);

        try {
            log.info("【请求统一认证法人用户信息】参数： {}", params);
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(params, headers);
            ResponseEntity<String> exchange = restTemplate.exchange(AuthCenterConst.AUTH_CENTER_ENTERPRISE_USER_INFO_URL, HttpMethod.POST, requestEntity, String.class);
            if(!exchange.getStatusCode().is2xxSuccessful()) {
                log.error("【请求统一认证法人用户信息】请求失败, http status :{}", exchange.getStatusCode());
                return null;
            }
            String body = exchange.getBody();
            log.info("【请求统一认证法人用户信息】返回： {}", body);

            JSONObject jsonObject = JSON.parseObject(body);
            if(jsonObject != null && !AuthCenterConst.AUTH_CENTER_SUCCESS_CODE.equals(jsonObject.getString("code"))) {
                log.error("【请求统一认证法人用户信息】接口返回code != 200");
                return null;
            }
            return jsonObject.getString("data");
        }catch (Exception e) {
            log.error("【请求统一认证法人用户信息】异常: {}", ExceptionUtil.getExceptionMessage(e));
            return null;
        }
    }

    // 获取自然人用户信息，返回加密的数据
    private String requestEncodeEnterpriseNatureUserInfo(String token, String sign, String timestamp) {

        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        params.add("app_id", AuthCenterConst.APP_ID);
        params.add("interface_id", "findPerUserByToken");
        params.add("version", "1.0");
        params.add("charset", "UTF-8");
        params.add("timestamp", timestamp);
        params.add("origin", "0");
        params.add("sign", sign);
        String bizContent = this.getBizContent("token", token);
        params.add("biz_content", bizContent);

        try {
            log.info("【请求统一认证自然人用户信息】参数： {}", params);
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(params, headers);
            ResponseEntity<String> exchange = restTemplate.exchange(AuthCenterConst.AUTH_CENTER_NATURE_USER_INFO_URL, HttpMethod.POST, requestEntity, String.class);
            if(!exchange.getStatusCode().is2xxSuccessful()) {
                log.error("【请求统一认证自然人用户信息】请求失败, http status :{}", exchange.getStatusCode());
                return null;
            }
            String body = exchange.getBody();
            log.info("【请求统一认证自然人用户信息】返回： {}", body);

            JSONObject jsonObject = JSON.parseObject(body);
            if(jsonObject != null && !AuthCenterConst.AUTH_CENTER_SUCCESS_CODE.equals(jsonObject.getString("code"))) {
                log.error("【请求统一认证自然人用户信息】接口返回code != 200");
                return null;
            }
            return jsonObject.getString("data");
        }catch (Exception e) {
            log.error("【请求统一认证自然人用户信息】异常: {}", ExceptionUtil.getExceptionMessage(e));
            return null;
        }
    }

    private AuthEnterpriseUserInfo decodeEnterpriseUserInfo(String data) {
        try {
            String content = SmCryptoUtil.sm2Decode(data, AuthCenterConst.sm2PrivateKey);
            log.info("【解密数据】解密数据： {}", content);
            if(StringUtils.isEmpty(content)) {
                log.error("【解密数据】解密数据为空");
                return null;
            }
            AuthCenterDecodeDataWrapper<String> dataWrapper = JSON.parseObject(content, new TypeReference<AuthCenterDecodeDataWrapper<String>>() {});
            if(!AuthCenterConst.DATA_SUCCESS_CODE.equals(dataWrapper.getRetcode())) {
                log.error("【解密数据获取】接口返回code != 000000, retcode:{}, msg:{}", dataWrapper.getRetcode(), dataWrapper.getMsg());
                return null;
            }

            return JSON.parseObject(dataWrapper.getData(),AuthEnterpriseUserInfo.class);
        }catch (Exception e) {
            log.error("【解密数据获取token】解密异常: {}", ExceptionUtil.getExceptionMessage(e));
            return null;
        }
    }

    private AuthNatureUserInfo decodeNatureUserInfo(String data) {
        try {
            String content = SmCryptoUtil.sm2Decode(data, AuthCenterConst.sm2PrivateKey);
            log.info("【解密自然用户数据】解密数据： {}", content);
            if(StringUtils.isEmpty(content)) {
                log.error("【解密自然用户数据】解密数据为空");
                return null;
            }
            AuthCenterDecodeDataWrapper<String> dataWrapper = JSON.parseObject(content, new TypeReference<AuthCenterDecodeDataWrapper<String>>() {});
            if(!AuthCenterConst.DATA_SUCCESS_CODE.equals(dataWrapper.getRetcode())) {
                log.error("【解密自然用户数据】接口返回code != 000000, retcode:{}, msg:{}", dataWrapper.getRetcode(), dataWrapper.getMsg());
                return null;
            }
            return JSON.parseObject(dataWrapper.getData(),AuthNatureUserInfo.class);
        }catch (Exception e) {
            log.error("【解密自然用户数据】解密异常: {}", ExceptionUtil.getExceptionMessage(e));
            return null;
        }
    }

    //
    @GetMapping("/testSM2")
    @ResponseBody
    public String testSM2() {
        String secret =
                "0406f22b62cf4fe9bb5655e9c0eb0abeed1fda59c85922fe1061962e26bda4ad57ffe2588b966a2bc3c86a9a1a26f4fff244a05e57046eb0a6134c3f197aaf49dc65d31990eaa27bda81aaeedd30ca8b0e9d8378c864df8151c598dc3c50ea16991b9cc31b3a5cc15a3557c1302b";
        String sm2PrivateKey = "00b82396992e8e5e739939df8f1b44fbb93231028490d4ffd2ec37ddabdf98801c";
        String content = SmCryptoUtil.sm2Decode(secret, sm2PrivateKey);
        return content;
    }


    public static void main(String[] args) {
        JSONObject jsonParam = new JSONObject();
        jsonParam.put("ticket", "123");
        System.out.println(jsonParam.toString());
        try {
            String secret =
                    "0406f22b62cf4fe9bb5655e9c0eb0abeed1fda59c85922fe1061962e26bda4ad57ffe2588b966a2bc3c86a9a1a26f4fff244a05e57046eb0a6134c3f197aaf49dc65d31990eaa27bda81aaeedd30ca8b0e9d8378c864df8151c598dc3c50ea16991b9cc31b3a5cc15a3557c1302b";
            String sm2PrivateKey = "00b82396992e8e5e739939df8f1b44fbb93231028490d4ffd2ec37ddabdf98801c";
            String content = SmCryptoUtil.sm2Decode(secret, sm2PrivateKey);
            System.out.println("解密数据：" + content);
        }catch (Exception e) {
            System.out.println(ExceptionUtil.getExceptionMessage(e));
        }
    }

}
